package tsinghua.smxq.mc;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import tsinghua.smxq.prototype.User;
import tsinghua.smxq.ui.MCScrollView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class FaceActivity extends Activity implements OnGestureListener,
		OnTouchListener {

	private TextView date_TextView;
	private ImageButton set_ImageButton, regist_ImageButton, login_ImageButton;
	private ViewFlipper viewFlipper;
	private boolean showNext = true;
	private boolean isRun = true;
	private int currentPage = 0;
	private final int SHOW_NEXT = 0011;
	private static final int FLING_MIN_DISTANCE = 50;
	private static final int FLING_MIN_VELOCITY = 0;
	private GestureDetector mGestureDetector;
	Thread thread;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.face_view);
		date_TextView = (TextView) findViewById(R.id.home_date_tv);
		date_TextView.setText(getDate());

		regist_ImageButton = (ImageButton) findViewById(R.id.reg_btn);
		regist_ImageButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(FaceActivity.this, RegisterActivity.class);
				startActivity(intent);
			}
		});
		login_ImageButton = (ImageButton) findViewById(R.id.login_btn);
		login_ImageButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				LayoutInflater factory = LayoutInflater.from(FaceActivity.this);
				final View loginDlgView = factory.inflate(R.layout.login_view,
						null);
				SharedPreferences userInfo = getSharedPreferences("user_info",
						0);

				EditText uname = (EditText) loginDlgView
						.findViewById(R.id.login_username);
				EditText upwd = (EditText) loginDlgView
						.findViewById(R.id.login_password);
				uname.setText(userInfo.getString("name", ""));
				upwd.setText(userInfo.getString("pass", ""));
				Builder builder = new AlertDialog.Builder(FaceActivity.this);
				builder.setIcon(R.drawable.login_dlg);
				builder.setTitle("欢迎登录");
				builder.setView(loginDlgView);
				builder.setPositiveButton("登录",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								EditText uname = (EditText) loginDlgView
										.findViewById(R.id.login_username);
								EditText upwd = (EditText) loginDlgView
										.findViewById(R.id.login_password);
								String suname = uname.getText().toString();
								String supwd = upwd.getText().toString();
								HttpClient httpclient = new DefaultHttpClient();
								List<NameValuePair> qparams = new ArrayList<NameValuePair>();
								qparams.add(new BasicNameValuePair("method",
										"login"));
								qparams.add(new BasicNameValuePair("username",
										suname));
								qparams.add(new BasicNameValuePair("password",
										supwd));
								URI uri;
								try {
									uri = URIUtils.createURI("http",
											Constants.serverIP, 8080,
											"MobileCityServer/UserServlet",
											URLEncodedUtils.format(qparams,
													"UTF-8"), null);
									HttpGet httpget = new HttpGet(uri);
									HttpResponse response = httpclient
											.execute(httpget);
									HttpEntity entity = response.getEntity();
									if (entity != null) {
										String contentString = EntityUtils
												.toString(entity);
										JSONObject o = new JSONObject(
												contentString);
										int status = o.getInt("status");
										JSONObject juser = o
												.getJSONObject("user");
										if (status == 1) {
											SharedPreferences userInfo = getSharedPreferences(
													"user_info", 0);
											userInfo.edit()
													.putString("name", suname)
													.commit();
											userInfo.edit()
													.putString("pass", supwd)
													.commit();
											Toast.makeText(FaceActivity.this,
													"登录成功！", Toast.LENGTH_LONG)
													.show();
											Session.user = new User();
											Session.user.setId(juser
													.getInt("id"));
											Session.user.setPassword(juser
													.getString("password"));
											if (juser.has("mobilePhone")) {
												Session.user.setMobilePhone(juser
														.getString("mobilePhone"));

											}
											if (juser.has("email")) {
												Session.user.setEmail(juser
														.getString("email"));

											}
											if (juser.has("gender")) {
												Session.user.setGender(juser
														.getInt("gender"));

											} else {
												Session.user.setGender(-1);
											}
											if (juser.has("userClass")) {

												Session.user.setUserClass(juser
														.getInt("userClass"));
											} else {
												Session.user.setUserClass(-1);
											}

											Session.user.setUserName(juser
													.getString("userName"));
											if (juser.has("birthday")
													&& juser.getString(
															"birthday")
															.compareTo("null") != 0) {
												JSONObject birth = juser
														.getJSONObject("birthday");
												Session.user
														.setBirthday(new Timestamp(
																birth.getInt("year"),
																birth.getInt("month"),
																birth.getInt("date"),
																birth.getInt("hours"),
																birth.getInt("minutes"),
																birth.getInt("seconds"),
																birth.getInt("nanos")));

											}
											Field field = dialog
													.getClass()
													.getSuperclass()
													.getDeclaredField(
															"mShowing");
											field.setAccessible(true);
											field.set(dialog, true);
											FaceActivity.this
													.startActivity(new Intent(
															FaceActivity.this,
															MobileCityActivity.class));
											thread.interrupt();
											FaceActivity.this.finish();
										} else {
											Toast.makeText(FaceActivity.this,
													"用户名/密码错误",
													Toast.LENGTH_LONG).show();
											try {
												Field field = dialog
														.getClass()
														.getSuperclass()
														.getDeclaredField(
																"mShowing");
												field.setAccessible(true);
												field.set(dialog, false);
											} catch (SecurityException e) {
												// TODO Auto-generated catch
												// block
												e.printStackTrace();
											} catch (NoSuchFieldException e) {
												// TODO Auto-generated catch
												// block
												e.printStackTrace();
											} catch (IllegalArgumentException e) {
												// TODO Auto-generated catch
												// block
												e.printStackTrace();
											} catch (IllegalAccessException e) {
												// TODO Auto-generated catch
												// block
												e.printStackTrace();
											}

										}

									}

								} catch (URISyntaxException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (ClientProtocolException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (SecurityException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (NoSuchFieldException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (IllegalArgumentException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (IllegalAccessException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						});
				builder.setNegativeButton("取消",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								Field field;
								try {
									field = dialog.getClass().getSuperclass()
											.getDeclaredField("mShowing");
									field.setAccessible(true);
									field.set(dialog, true);
								} catch (SecurityException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (NoSuchFieldException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (IllegalArgumentException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (IllegalAccessException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

							}
						});
				AlertDialog dlg = builder.create();
				dlg.show();

			}
		});
		viewFlipper = (ViewFlipper) findViewById(R.id.mViewFliper_vf);
		mGestureDetector = new GestureDetector(this);
		viewFlipper.setOnTouchListener(this);
		viewFlipper.setLongClickable(true);
		viewFlipper.setOnClickListener(clickListener);
		displayRatio_selelct(currentPage);

		MCScrollView MCScrollView = (MCScrollView) findViewById(R.id.viewflipper_scrollview);
		MCScrollView.setOnTouchListener(onTouchListener);
		MCScrollView.setGestureDetector(mGestureDetector);
		thread = new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				while (isRun) {
					try {
						Thread.sleep(1000 * 8);
						Message msg = new Message();
						msg.what = SHOW_NEXT;
						mHandler.sendMessage(msg);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						isRun = false;
						// e.printStackTrace();
					}
				}
			}

		};

		thread.start();
	}

	private OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
		}
	};
	private OnTouchListener onTouchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			return mGestureDetector.onTouchEvent(event);
		}
	};

	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case SHOW_NEXT:
				if (showNext) {
					showNextView();
				} else {
					showPreviousView();
				}
				break;

			default:
				break;
			}
		}

	};

	private String getDate() {
		Date date = new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
		int w = c.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0) {
			w = 0;
		}
		String mDate = c.get(Calendar.YEAR) + "年" + (c.get(Calendar.MONTH) + 1)
				+ "月" + c.get(Calendar.DATE) + "日  " + weekDays[w];
		return mDate;
	}

	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// TODO Auto-generated method stub
		if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
			showNextView();
			showNext = true;
			// return true;
		} else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
			showPreviousView();
			showNext = false;
			// return true;
		}
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		return mGestureDetector.onTouchEvent(event);
	}

	private void showNextView() {

		viewFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
				R.anim.push_left_in));
		viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
				R.anim.push_left_out));
		viewFlipper.showNext();
		currentPage++;
		if (currentPage == viewFlipper.getChildCount()) {
			displayRatio_normal(currentPage - 1);
			currentPage = 0;
			displayRatio_selelct(currentPage);
		} else {
			displayRatio_selelct(currentPage);
			displayRatio_normal(currentPage - 1);
		}
		Log.e("currentPage", currentPage + "");

	}

	private void showPreviousView() {
		displayRatio_selelct(currentPage);
		viewFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
				R.anim.push_right_in));
		viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
				R.anim.push_right_out));
		viewFlipper.showPrevious();
		currentPage--;
		if (currentPage == -1) {
			displayRatio_normal(currentPage + 1);
			currentPage = viewFlipper.getChildCount() - 1;
			displayRatio_selelct(currentPage);
		} else {
			displayRatio_selelct(currentPage);
			displayRatio_normal(currentPage + 1);
		}
		Log.e("currentPage", currentPage + "");
	}

	private void displayRatio_selelct(int id) {
		int[] ratioId = { R.id.home_ratio_img_04, R.id.home_ratio_img_03,
				R.id.home_ratio_img_02, R.id.home_ratio_img_01 };
		ImageView img = (ImageView) findViewById(ratioId[id]);
		img.setSelected(true);
	}

	private void displayRatio_normal(int id) {
		int[] ratioId = { R.id.home_ratio_img_04, R.id.home_ratio_img_03,
				R.id.home_ratio_img_02, R.id.home_ratio_img_01 };
		ImageView img = (ImageView) findViewById(ratioId[id]);
		img.setSelected(false);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			isRun = false;
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		finish();
		super.onDestroy();
	}

}
